package com.example.blog.interceptor;

import com.example.blog.pojo.User;
import com.example.blog.service.AdminService;
import com.example.blog.service.UserService;
import com.example.blog.util.TokenUtil.JwtUtils;
import com.example.blog.util.TokenUtil.spiltUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;
    @Resource
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取用户登录凭证
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    String token = cookie.getValue();
                    Claims claims;
                    String pe;// 获取用户登录名
                    String uri = request.getRequestURI();
                    log.info("访问uri => " + uri);

                    if (token != null && (claims = JwtUtils.parseJWT(token)) != null && (pe = JwtUtils.getUserName(claims)) != null) {
                        String userName = spiltUtils.getUserName(pe);
                        // 已登录
                        User user = userService.getByUserName(userName);
                        if (user == null) {
                            log.info("用户不存在或被删除");
                            // 已经登录的用户被删除了?
                            return false;
                        }
                        if (user.getStatus()==1){
                            log.info("用户已被禁用！");
                            return false;
                        }
                        // 在这里可以根据需要进行权限验证等操作
                        log.info("鉴权通过 => " + uri);
                        return true;
                    } else {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    }
                    log.info("鉴权失败 => " + uri);
                    return false;
                }

            }
        }
        return false;
    }


}
